﻿using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;
namespace Zinnia.Common
{
    /// <summary>
    /// 序列化帮助类
    /// </summary>
    public static class SerializerHelper<T>
    {
        private static XmlSerializer _xmlSerializer = new XmlSerializer(typeof(T));

        /// <summary>
        /// XML反序列化
        /// </summary>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T XmlDeserialize(string xml)
        {
            try
            {
                using (StringReader stringReader = new StringReader(xml))
                {
                    return (T)_xmlSerializer.Deserialize(stringReader);
                }
            }
            catch (Exception ex)
            {
                throw new ZinniaException(ZinniaErrorCode.XmlSerrializeError, "XmlDeserialize Exception", ex);
            }
        }
        /// <summary>
        /// XML序列化
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string XmlSerialize(T obj)
        {
            try
            {
                using (MemoryStream memoryStream = new MemoryStream())
                {
                    XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, new UTF8Encoding(false))
                    {
                        Formatting = Formatting.Indented
                    };
                    _xmlSerializer.Serialize(xmlTextWriter, obj);
                    xmlTextWriter.Flush();
                    xmlTextWriter.Close();
                    UTF8Encoding uTF8Encoding = new UTF8Encoding(false, true);
                    return uTF8Encoding.GetString(memoryStream.ToArray());
                }
            }
            catch (Exception ex)
            {
                throw new ZinniaException(ZinniaErrorCode.XmlSerrializeError, "XmlSerialize Exception", ex);
            }
        }
    }
}
